package com.ruoyi.system.controller;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysCompany;
import com.ruoyi.system.service.ISysCompanyService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * 公司信息
 *
 * @author xlss
 */
@RestController
@RequestMapping("/company")
public class SysCompanyController extends BaseController {
    @Autowired
    private ISysCompanyService companyService;

    /**
     * 获取公司列表
     */
    @RequiresPermissions("system:company:list")
    @GetMapping("/list")
    public AjaxResult list(SysCompany company) {
        List<SysCompany> companys = companyService.selectCompanyList(company);
        return AjaxResult.success(companys);
    }

    /**
     * 查询公司列表（排除节点）
     */
    @RequiresPermissions("system:company:list")
    @GetMapping("/list/exclude/{companyId}")
    public AjaxResult excludeChild(@PathVariable(value = "companyId", required = false) Long companyId) {
        List<SysCompany> companys = companyService.selectCompanyList(new SysCompany());
        Iterator<SysCompany> it = companys.iterator();
        while (it.hasNext()) {
            SysCompany d = (SysCompany) it.next();
            if (d.getCompanyId().intValue() == companyId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), companyId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(companys);
    }

    /**
     * 根据公司编号获取详细信息
     */
    @RequiresPermissions("system:company:query")
    @GetMapping(value = "/{companyId}")
    public AjaxResult getInfo(@PathVariable Long companyId) {
        companyService.checkCompanyDataScope(companyId);
        return AjaxResult.success(companyService.selectCompanyById(companyId));
    }

    /**
     * 获取公司下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysCompany company) {
        List<SysCompany> companys = companyService.selectCompanyList(company);
        return AjaxResult.success(companyService.buildCompanyTreeSelect(companys));
    }

    /**
     * 加载对应角色公司列表树
     */
    @GetMapping(value = "/roleCompanyTreeselect/{roleId}")
    public AjaxResult roleCompanyTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysCompany> companys = companyService.selectCompanyList(new SysCompany());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", companyService.selectCompanyListByRoleId(roleId));
        ajax.put("companys", companyService.buildCompanyTreeSelect(companys));
        return ajax;
    }

    /**
     * 新增公司
     */
    @RequiresPermissions("system:company:add")
    @Log(title = "公司管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysCompany company) {
        if (UserConstants.NOT_UNIQUE.equals(companyService.checkCompanyNameUnique(company))) {
            return AjaxResult.error("新增公司'" + company.getCompanyName() + "'失败，公司名称已存在");
        }
        company.setCreateBy(SecurityUtils.getUsername());
        return toAjax(companyService.insertCompany(company));
    }

    /**
     * 修改公司
     */
    @RequiresPermissions("system:company:edit")
    @Log(title = "公司管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysCompany company) {
        Long companyId = company.getCompanyId();
        companyService.checkCompanyDataScope(companyId);
        if (UserConstants.NOT_UNIQUE.equals(companyService.checkCompanyNameUnique(company))) {
            return AjaxResult.error("修改公司'" + company.getCompanyName() + "'失败，公司名称已存在");
        } else if (company.getParentId().equals(companyId)) {
            return AjaxResult.error("修改公司'" + company.getCompanyName() + "'失败，上级公司不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, company.getStatus()) && companyService.selectNormalChildrenCompanyById(companyId) > 0) {
            return AjaxResult.error("该公司包含未停用的子公司！");
        }
        company.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(companyService.updateCompany(company));
    }

    /**
     * 删除公司
     */
    @RequiresPermissions("system:company:remove")
    @Log(title = "公司管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{companyId}")
    public AjaxResult remove(@PathVariable Long companyId) {
        if (companyService.hasChildByCompanyId(companyId)) {
            return AjaxResult.error("存在下级公司,不允许删除");
        }
        if (companyService.checkCompanyExistUser(companyId)) {
            return AjaxResult.error("公司存在用户,不允许删除");
        }
        companyService.checkCompanyDataScope(companyId);
        return toAjax(companyService.deleteCompanyById(companyId));
    }
}
